package com.lhy.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lhy.domain.Result;
import com.lhy.domain.Student;
import com.lhy.service.IUserService;
import com.lhy.session.OnlineCounter;



@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	private IUserService userService;
	@RequestMapping("")
	public String toIndex(HttpServletRequest request, Model model){
		return "login";
	}
	@RequestMapping("/queryOnlineCount")
	public @ResponseBody
	Map<String, Object> queryOnlineCount(HttpSession session)  {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Result result=new Result();
		result.setCode("1");
		result.setDes("成功");
		
		try{
			returnMap.put("onlineuserCount", OnlineCounter.getOnline());
		}catch(Exception e){
				result.setCode("0");
				result.setDes(e.getMessage());
			
		}
		returnMap.put("result", result);
		
		return returnMap;
	}
	@RequestMapping("/do")
	public @ResponseBody
	Map<String, Object> login(HttpSession session,String username, String password)  {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Result result=new Result();
		result.setCode("1");
		result.setDes("成功");
		
		try{
			Student user = new Student();
			user = userService.selectByUserNameANDUserpwd(username, password);
			
			if(user == null){
				result.setCode("0");
				result.setDes("用户名或密码错误，请重新输入！");
				returnMap.put("result", result);
				return returnMap;
			}
			session.setAttribute("img", user.getImg());
			session.setAttribute("nickname", user.getNickname());
			//session.setAttribute("nickname", user.getNickname());
			session.setAttribute("usersequence", user.getSequence());
			System.out.println(OnlineCounter.getOnline());
			returnMap.put("onlineuserCount", OnlineCounter.getOnline());
			returnMap.put("user", user);
		}catch(Exception e){
				result.setCode("0");
				result.setDes(e.getMessage());
			
		}
		returnMap.put("result", result);
		
		return returnMap;
	}
	@RequestMapping("/check")
	public @ResponseBody
	Map<String, Object> check(HttpSession session,String username)  {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Result result=new Result();
		result.setCode("1");
		result.setDes("成功");
		
		try{
			Student user = userService.selectByUserName(username);
			returnMap.put("user", user);
		}catch(Exception e){
				result.setCode("0");
				result.setDes(e.getMessage());
			
		}
		returnMap.put("result", result);
		
		return returnMap;
	}
}
